package com.example.test.utils;

import com.example.test.domain.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

public class SecurityUtils {
    public static Optional<User> getCurrentUser(){
        SecurityContext securityContext = SecurityContextHolder.getContext();
        if(securityContext == null) return Optional.empty();
        Authentication authentication = securityContext.getAuthentication();
        if(authentication == null) return Optional.empty();
        Object principal = authentication.getPrincipal();
        if(principal instanceof User){
            return Optional.of((User) principal);
        }
        return Optional.empty();
    }
}
